<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Share Buffer</title>
  </head>
  <body>
    <script src="./node_modules/coi-serviceworker/coi-serviceworker.min.js"></script>
    <script>
      const workerScript = `
        self.onmessage = ({data}) => {
        const view = new Uint32Array(data);
        // 执行1 000 000 次加操作
        for (let i = 0; i < 100; ++i) {
        // 线程不安全加操作会导致资源争用
        view[0] += 1;
        }
        self.postMessage(null);
        };
      `;
      const workerScriptBlobUrl = URL.createObjectURL(new Blob([workerScript]));
      // 创建容量为4 的工作线程池
      const workers = [];
      for (let i = 0; i < 4; ++i) {
        workers.push(new Worker(workerScriptBlobUrl));
      }
      // 在最后一个工作线程完成后打印出最终值
      let responseCount = 0;
      for (const worker of workers) {
        worker.onmessage = () => {
          console.log(responseCount)
          if (++responseCount == workers.length) {
            console.log(`Final buffer value: ${view[0]}`);
          }
        };
      }
      // 初始化SharedArrayBuffer
      const sharedArrayBuffer = new SharedArrayBuffer(4);
      const view = new Uint32Array(sharedArrayBuffer);
      view[0] = 1;
      // 把SharedArrayBuffer 发送到每个工作线程
      for (const worker of workers) {
        worker.postMessage(sharedArrayBuffer);
      }
    </script>
  </body>
</html>
